<!--
 * @Date: 2023-08-18 18:38:01
 * @LastEditors: 景冰川 961166897@qq.com
 * @LastEditTime: 2023-08-24 16:55:20
 * @FilePath: \part-cloud-appd:\project\company\veteran-cadre-app\src\components\sonic-view.vue
-->
<script setup lang="ts">
import { formatSeconds } from '@/util/utils'

const props = defineProps({
  audioUrl: {
    type: String,
    default: '',
    required: true,
  },
  width: {
    type: String,
    default: '686rpx',
  },
})
const innerAudioContext = uni.createInnerAudioContext()

const isPlay = ref(false)
const audioDurationStr = ref('')
async function onPlayAudio() {
  if (isPlay.value === true)
    return

  if (!props.audioUrl) {
    uni.showToast({
      title: '没有语音地址',
      icon: 'none',
    })
    return
  }
  // const innerAudioContext = uni.createInnerAudioContext()
  innerAudioContext.autoplay = true
  innerAudioContext.src = props.audioUrl
  innerAudioContext.play()
  innerAudioContext.onEnded(() => {
    onPauseAudio()
  })

  innerAudioContext.onError((res) => {
    onPauseAudio()
    uni.showToast({
      title: res,
      icon: 'error',
    })
  })
  innerAudioContext.onTimeUpdate(() => {
    const { duration } = innerAudioContext
    audioDurationStr.value = formatSeconds(Number(duration.toFixed(0)))
  })
  isPlay.value = true
}
watch(
  () => props.audioUrl,
  (v) => {
    audioDurationStr.value = ''
    if (v === '')
      onDestroyAudio()
  })

onUnload(() => {
  innerAudioContext.pause()
})

onHide(() => {
  onDestroyAudio()
})

onUnmounted(() => {
  onDestroyAudio()
})
function onDestroyAudio() {
  if (isPlay.value === true) {
    innerAudioContext.pause()
    innerAudioContext.destroy()
    isPlay.value = false
  }
}
function onPauseAudio() {
  innerAudioContext.pause()
  isPlay.value = false
}
</script>

<template>
  <view v-if="audioUrl" class="mx-a bg-#68D480 rounded-16rpx flex h-80rpx items-center" :class="[`w-${props.width}`]" @click.stop="onPlayAudio">
    <image
      class="ml-32rpx block h-42rpx w-30rpx"
      src="@/static/images/home/yy@2x.png"
      mode="scaleToFill"
    />
    <sonic-animation :is-play="isPlay" class="ml-30rpx" />
    <view class="ml-30rpx">
      {{ audioDurationStr }}
    </view>
  </view>
</template>
